package cn.nyse.ktc_user.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import wfw.cn.ktc_common.unit.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    Environment environment;

    @Autowired
    JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String auth = request.getHeader("auth");
        String prefix = environment.getProperty("jwt.config.prefix");
        if (!auth.startsWith(prefix)){
            return false;
        }
        String token = auth.substring(prefix.length());
        Claims claims = jwtUtil.parseJWT(token);
        if (!"user".equals(claims.get("role"))){
            return false;
        }
        return true;
    }
}
